package online.chazi.bootplus.commons.retrier;

import lombok.extern.slf4j.Slf4j;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-04-13 15:32
 */
@Slf4j
public class SimpleRetrier {

    private int[] intervalSeconds = new int[]{30, 60, 300, 600, 1200, 3600};
    private Retrier retrier;
    private Thread thread;

    public SimpleRetrier(Retrier retrier) {
        this.retrier = retrier;
        this.thread = new Thread(() -> {
            int next = -1;
            boolean isSuccess;
            do {
                try {
                    retrier.process();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    next++;
                }
            } while (!(isSuccess = retrier.isSuccess()) && sleep(next));
            retrier.complete(isSuccess);
            if (!isSuccess) {
                retrier.fail();
            }
        });
        this.thread.setDaemon(true);
    }

    public SimpleRetrier withIntervalSeconds(int[] intervalSeconds) {
        this.intervalSeconds = intervalSeconds;
        return this;
    }

    public void interrupt() {
        this.thread.interrupt();
    }

    public void start() {
        this.thread.start();
    }

    private boolean sleep(int next) {
        if (next >= intervalSeconds.length) return false;
        try {
            Thread.sleep(intervalSeconds[next] * 1000L);
        } catch (InterruptedException e) {
            //
        }
        return true;
    }

}
